<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\common\support;

use think\facade\App;
use think\facade\Config;

class FileUtil{

	/**
	 * 获取保存文件名
	 *
	 * @param string $suffix
	 * @param mixed  $rule
	 * @return string
	 */
	public static function buildSaveName($suffix, $rule = 'date'){
		$basePath = date('Ymd').DIRECTORY_SEPARATOR.md5(microtime(true));
		switch($rule){
			case 'date':
				$path = date('Ymd').DIRECTORY_SEPARATOR.md5(microtime(true));
				break;
			default:
				if(in_array($rule, hash_algos())){
					$hash = hash($rule, $basePath);
					$path = substr($hash, 0, 2).DIRECTORY_SEPARATOR.substr($hash, 2);
				}elseif(is_callable($rule)){
					$path = call_user_func($rule);
				}else{
					$path = date('Ymd').DIRECTORY_SEPARATOR.md5(microtime(true));
				}
		}

		if($suffix){
			$path .= '.'.$suffix;
		}

		return $path;
	}

	/**
	 * @return \xin\oss\ObjectStorageInterface
	 */
	protected static function resolveOSS(){
		/** @var \xin\oss\ObjectStorageInterface $oss */
		$oss = App::make('oss');
		return $oss;
	}

	/**
	 * 生成结果
	 *
	 * @param mixed $result
	 * @return string
	 */
	protected static function resolveResult($result){
		if(isset($result['key'])){
			$path = $result['key'];
			$driver = Config::get('filesystem.driver');
			$drivers = Config::get('filesystem.drivers');
			if(isset($drivers[$driver]['domain'])){
				$path = $drivers[$driver]['domain'].'/'.$path;
			}
		}else{
			$path = $result['url'];
		}

		return $path;
	}

	/**
	 * 上传本地文件
	 *
	 * @param string $targetKey
	 * @param string $localKey
	 * @return string
	 * @throws \xin\oss\ObjectStorageException
	 */
	public static function cloud($targetKey, $localKey){
		if($localKey instanceof \SplFileInfo){
			$localKey = $localKey->getRealPath();
		}

		$result = self::resolveOSS()->uploadFile(
			$targetKey,
			$localKey
		);

		return self::resolveResult($result);
	}

	/**
	 * 上传二进制数据
	 *
	 * @param string $targetKey
	 * @param mixed  $data
	 * @return string
	 * @throws \xin\oss\ObjectStorageException
	 */
	public static function cloudData($targetKey, $data){
		$result = self::resolveOSS()->uploadData(
			$targetKey,
			$data
		);

		return self::resolveResult($result);
	}

}
